import axios from 'axios'
import Cookie from '@/utils/auth.js'
import { Toast, removeProperty } from '@/utils/tools.js';
import { baseURL } from '@/common/baseconfig.js'

let reqList = []

/**
 * 阻止重复请求
 * @param {array} reqList - 请求缓存列表
 * @param {string} url - 当前请求地址
 * @param {function} cancel - 请求中断函数
 * @param {string} errorMessage - 请求中断时需要显示的错误信息
 */
const stopRepeatRequest = function(reqList, url, cancel, errorMessage) {
	const errorMsg = errorMessage || ''
	for (let i = 0; i < reqList.length; i++) {
		if (reqList[i] === url) {
			cancel(errorMsg)
			return
		}
	}
	reqList.push(url)
}

/**
 * 允许某个请求可以继续进行
 * @param {array} reqList 全部请求列表
 * @param {string} url 请求地址
 */
const allowRequest = function(reqList, url) {
	for (let i = 0; i < reqList.length; i++) {
		if (reqList[i] === url) {
			reqList.splice(i, 1)
			break
		}
	}
}

const service = axios.create({
	baseURL: baseURL, // url = base url + request url
	timeout: 15000 // request timeout
});

// request interceptor
service.interceptors.request.use(
	config => {
		if (config.mask) {
			// #ifdef APP-PLUS
			plus.nativeUI.showWaiting();
			// #endif
			// #ifndef APP-PLUS
			uni.showLoading({
				mask: true,
				title: '加载中'
			})
			// #endif
		}
		config.headers = {
			'Token': Cookie.get('Token') || '0',
			'Content-Type': 'application/json',
		};
		let cancel
		// 设置cancelToken对象
		config.cancelToken = new axios.CancelToken(function(c) {
			cancel = c
		})
		// 阻止重复请求。当上个请求未完成时，相同的请求不会进行
		stopRepeatRequest(reqList, config.url, cancel, `${config.url} 请求被中断`)
		return config;

	},
	error => {
		// store.commit('common/SET_LOADING');
		// do something with request error
		// console.log(error); // for debug
		return Promise.reject(error)
	}
);

// response interceptor
service.interceptors.response.use(
	response => {
		// #ifdef APP-PLUS
		plus.nativeUI.closeWaiting();
		// #endif
		// #ifndef APP-PLUS
		uni.hideLoading();
		// #endif
		// successHandler(response)

		// 增加延迟，相同请求不得在短时间内重复发送
		setTimeout(() => {
			allowRequest(reqList, response.config.url)
		}, 300)

		if (!response.config.closeLoad) {
			// store.commit('common/CLOSE_LOADING');
		}
		const res = response.data;
		if (res.code == 'notlogin') {
			// store.commit('user/REMOVE_TOKEN');
			// router.push({ name: 'login' });
			return false
		}
		if (res.code == 'SYS-ERROR') {
			return false
		}
		if (!res.success) Toast(res.message)
		return res;
	},
	error => {
		console.log('error---', error)
		// store.commit('common/SET_LOADING');
		if (error.name == 'CanceledError') return
		Toast(error.message)
		return Promise.reject(error)
	}
);

export default service